<template>
	<view>
		<view class="uni-padding-wrap uni-common-mt">
			<view>设备id：{{deviceId}} iemi {{plus.device.imsi}} imsi {{plus.device.model}}model {{plus.device.vendor}} vendor {{plus.device.uuid}} uuid</view>
			<view>appid {{plus.runtime.appid}}</view>
			<view>launcher {{plus.runtime.launcher}}</view>
			<view>origin {{plus.runtime.origin}}</view>
			<view>channel {{plus.runtime.channel}}</view>
			<view>innerVersion {{plus.runtime.innerVersion}}</view>
			<view>processId {{plus.runtime.processId}}</view>
			<view>uniVersion {{plus.runtime.uniVersion}}</view>
			<view>到期时间：{{deviceInfo.endTime}} 23:59:59 最大挂单数量：{{deviceInfo.maxNumber}}</view>
			<view>软件状态： <span style="color: #09BB07;">{{totalStatus}}</span></view>
			<view>等待抢购的星座：{{waitStarList}}</view>
		</view>
		<button type="warn" @click="buyClickHandle" style="margin: 10px;">购买</button>

		<!-- tableData -->
		<view>
			<uni-list>
				<uni-swipe-action v-for="(v,index) in tableData" :options="options" @click="cardClickHandle($event, v, index)">
					<uni-card :title="(index+1) + '号 ' + v.phone + v.realname" note="111" :extra="result" is-shadow="true">
						<view>已预约的星座：{{JSON.stringify(v.preBuyList)}}</view>
						<view>等待抢购的星座：{{JSON.stringify(v.option)}}</view>
						<view>抢购成功的星座：<span style="color: red">{{JSON.stringify(v.successStar)}}</span></view>
						<template v-slot:footer>
							<view class="footer-box">
								<view>状态: <span :style="{color: v.status === '未登录' ? 'red' : 'green'}">{{v.status}}</span></view>
							</view>
						</template>
					</uni-card>
				</uni-swipe-action>
			</uni-list>
		</view>

		<uni-popup ref="popup" type="center" @change="comEditAccountChange">
			<com-editAccount v-if="isEditAccountShow" @sendComEditAccount="sendComEditAccount" :optionList="optionList"
			 :userInfo="userInfo"></com-editAccount>
		</uni-popup>
		<uni-popup ref="buyPage" type="center" @change="comBuyPageChange">
			<com-buy-page v-if="isBuyPageShow" :deviceId="deviceId"></com-buy-page>
		</uni-popup>
		<view>
			<uni-fab :pattern="pattern" :content="content" :horizontal="horizontal" :vertical="vertical" :direction="direction"
			 @trigger="trigger"></uni-fab>
		</view>
	</view>
</template>

<script>
	import uniPopup from "@/components/uni-popup/uni-popup.vue"
	import uniSwipeAction from "@/components/uni-swipe-action/uni-swipe-action.vue"
	import uniIcons from "@/components/uni-icons/uni-icons.vue"
	import uniCard from "@/components/uni-card/uni-card"
	import uniList from "@/components/uni-list/uni-list.vue"
	import uniFab from '@/components/uni-fab/uni-fab.vue';
	import uniListItem from "@/components/uni-list-item/uni-list-item.vue"
	import comEditAccount from "./component/editAccount.vue"
	import comBuyPage from "./component/buyPage.vue"
	import api from "../../api/api.js"
	import Vue from 'vue'

	let isDeviceId
	let endTime
	let macInfo
	export default {
		components: {
			uniPopup,
			comEditAccount,
			uniSwipeAction,
			uniList,
			uniListItem,
			uniCard,
			uniIcons,
			uniFab,
			comBuyPage
		},
		data() {
			return {
				totalStatus: "已停止",
				opIndex: -1,
				isBuyPageShow: false,
				preBuyLoading: false,
				title: 'Hello1',
				isEditAccountShow: false,
				deviceInfo: {},
				timmerList: [],
				waitStarList: [],
				tableData: [],
				optionList: [],
				userInfo: {},
				plus: {},
				deviceId: "",
				options: [{
					text: '编辑',
					style: {
						backgroundColor: '#007AFF'
					}
				}, {
					text: '删除',
					style: {
						backgroundColor: '#dd524d'
					}
				}],
				horizontal: 'left',
				vertical: 'bottom',
				direction: 'horizontal',
				pattern: {
					color: '#7A7E83',
					backgroundColor: '#fff',
					selectedColor: '#007AFF',
					buttonColor: "#007AFF"
				},
				content: [{
						iconPath: '/static/template.png',
						selectedIconPath: '/static/plus.png',
						text: '添加账号',
						active: true
					},
					{
						iconPath: '/static/component.png',
						selectedIconPath: '/static/c1.png',
						text: '登录',
						active: true
					},
					{
						iconPath: '/static/api.png',
						selectedIconPath: '/static/c2.png',
						text: '预约',
						active: true
					},
					{
						iconPath: '/static/template.png',
						selectedIconPath: '/static/location.png',
						text: '查看结果',
						active: true
					}
				]
			}
		},
		onLoad() {
			this.init()
			// this.deviceId = plus.device.imei.split(",")[0];
		},
		mounted() {},
		onPullDownRefresh() {
			//监听下拉刷新动作的执行方法，每次手动下拉刷新都会执行一次
			console.log('refresh');
			this.init()
			setTimeout(function() {
				uni.stopPullDownRefresh(); //停止下拉刷新动画
			}, 1000);
		},
		methods: {
			init() {
				this.plus = plus
				this.totalStatus = "正在启动中..."
				this.isLimit = false
				console.log("uuid",plus.device.uuid)
				console.log("imei",plus.device.imei)
				this.deviceId = plus.device.imei.split(",")[0];
				// if (plus.device.imsi) {
				// 	uni.showToast({
				// 		title: "不要开分身",
				// 		icon: "none",
				// 		duration: 2000
				// 	})
				// 	return
				// }
				// this.deviceId = "860410036876654";
				api.getConfigJson().then(res => {
					console.log(res)
					this.deviceList = res.data
					const deviceInfo = this.deviceList.find(device => device.deviceId === this.deviceId)
					if (deviceInfo) {
						this.deviceInfo = deviceInfo
						isDeviceId = true
						endTime = new Date(deviceInfo.endTime)
						endTime.setHours(23)
						endTime.setMinutes(59)
						endTime.setSeconds(59)
						endTime = endTime.getTime()
						const tempTableData = uni.getStorageSync('tableData');
						if (tempTableData) {
							console.log("123213213213213213")
							tempTableData.map(item => {
								item.status = "未登录"
								item.successStar = []
								item.preBuyList = []
								item.result = ""
							})
							this.tableData = tempTableData
						}
						if (this.tableData.length > deviceInfo.maxNumber) {
							this.tableData = this.tableData.slice(0, deviceInfo.maxNumber)
						}
						// 循环获取token并调用获取星座详情接口
						this.cycleGetInit()
					} else {
						this.totalStatus = "启动失败"
						this.isLimit = true
						uni.showModal({
							title: '提示',
							content: `请购买后使用，若已购买只允许在1台电脑上使用`,
							showCancel: false,
							success: function(res) {
								if (res.confirm) {
									console.log('用户点击确定');
								} else if (res.cancel) {
									console.log('用户点击取消');
								}
							}
						});
					}
				})
			},
			cycleGetInit() {
				api.loginApi(13883609487, "l123456789").then(res => {
					this.commonToken = res.data.token
					this.cycleGetStarInfo(this.commonToken)
				}).catch(() => {
					setTimeout(() => {
						this.cycleGetInit()
					}, 5000)
				})
			},
			// 循环获取星座详情并创建好定时器，到时间抢单
			cycleGetStarInfo(commonToken) {
				api.getStarInfoApi(commonToken).then(res => {
					console.log(11111111)
					this.optionList = res.data.cat
					this.initTime = Number(res.time * 1000)
					// 判断权限
					if (!this.auth()) {
						this.isLimit = true
						return
					}
					this.createTimmerList()
				}).catch(e => {
					console.log(2)
					setTimeout(() => {
						this.cycleGetStarInfo(commonToken)
					}, 500)
				})
			},
			// 创建定时器列表并倒计时
			createTimmerList() {
				this.totalStatus = "启动成功，请登录并预约，到时会自动抢购"
				this.optionList.map(starInfo => {
					const staticTime = this.getTime(starInfo.adopt_begin_time)
					console.log(5555555)
					if (staticTime > this.initTime) {
						const timmer = setTimeout(() => {
							this.timmerList.splice(this.timmerList.findIndex(o => o === timmer), 1)
							this.waitStarList.splice(this.waitStarList.findIndex(o => o === starInfo.name), 1)
							this.timesUp(starInfo)
						}, staticTime - this.initTime + 50)
						// }, 0)
						this.timmerList.push(timmer)
						this.waitStarList.push(starInfo.name)
					}
				})
			},
			// 获取静态时间
			getTime(timeString) {
				// this.getNowTime().then(data => {
				//     console.log("data", data)
				// })
				const hours = timeString.split(":")[0]
				const min = timeString.split(":")[1]
				const staticTime = new Date()
				staticTime.setHours(hours)
				staticTime.setMinutes(min)
				staticTime.setSeconds(0)
				staticTime.setMilliseconds(0)
				// console.log("staticTime", staticTime)
				return staticTime.getTime()
			},
			timesUp(starInfo) {
				this.tableData.map((userInfo, index) => {
					// 清空结果
					this.$set(userInfo, "result", "")
					userInfo.index = index
					// 1.判断当前订单是否勾选 2.抢单
					if (userInfo.option && userInfo.option.find(name => name === starInfo.name)) {
						setTimeout(() => {
							this.cycleGetNew(userInfo, starInfo, userInfo.token)
						}, 5000 * Math.random())
						this.totalStatus = starInfo.name + "已抢购，请持续关注结果"
					}
					// 获取抢购成功但未付款的星座
				})
			},
			cycleGetNew(userInfo, starInfo, token) {
				api.getApi(starInfo.id, token).then(res => {
					console.log("res", res.data.code, res.data.msg, res.data)
					if (res.data.code === 0) {
						this.$set(userInfo, "result", starInfo.name + "已抢购，5分钟后点击一键检查漏单查看结果")
					} else {
						setTimeout(() => {
							this.cycleGetNew(userInfo, starInfo, token)
						}, 1000)
					}
				}).catch(e => {
					setTimeout(() => {
						this.cycleGetNew(userInfo, starInfo, token)
					}, 500)
				})
			},
			auth() {
				// 1.判断时间是否到期
				console.log("endTie", new Date(endTime))
				console.log("initTime", new Date(this.initTime))
				const isEnd = this.initTime < endTime || endTime === "*"
				if (!isEnd) {
					this.totalStatus = "启动失败"
					uni.showModal({
						title: '提示',
						content: `已过期，请继续购买后使用`,
						showCancel: false,
						success: function(res) {
							if (res.confirm) {
								console.log('用户点击确定');
							} else if (res.cancel) {
								console.log('用户点击取消');
							}
						}
					});
					return false
				}
				// 2.判断是否是正确的mac地址
				if (!isDeviceId) {
					this.totalStatus = "启动失败"
					uni.showModal({
						title: '提示',
						content: `请购买后使用，若已购买只允许在1台电脑上使用`,
						showCancel: false,
						success: function(res) {
							if (res.confirm) {
								console.log('用户点击确定');
							} else if (res.cancel) {
								console.log('用户点击取消');
							}
						}
					});
					return false
				}
				return true
			},
			openPopup() {
				this.$refs.popup.open()
			},
			closePopup() {
				this.$refs.popup.close()
			},
			sendComEditAccount(formData) {
				console.log("formData", formData)
				console.log("this.userInfo", this.userInfo)
				this.closePopup()
				console.log("this.opIndex", this.opIndex)
				if (this.opIndex !== -1) {
					// Vue.set(this.tableData[this.opIndex], "option", formData.option)
					console.log("this.tableData", this.tableData[this.opIndex])
					console.log("formData.option", formData.option)
					this.tableData[this.opIndex] = formData
					this.$forceUpdate()
				} else {
					this.tableData.push(formData)
				}
				this.setLocalStorage()
			},
			cardClickHandle(e, userInfo, index) {
				console.log(e)
				if (e.index === 1) { // 删除
					this.tableData.splice(index, 1)
					this.setLocalStorage()
				} else if (e.index === 0) { // 编辑
					this.userInfo = this.tableData[index]
					console.log("xxxxxxxx", this.userInfo)
					this.opIndex = index
					this.openPopup()
				}
			},
			setLocalStorage() {
				uni.setStorageSync('tableData', this.tableData);
			},
			refreshClickHandle() {
				window.Location.reload()
			},
			trigger(e) {
				if (this.isLimit) {
					uni.showModal({
						title: '提示',
						content: `请购买后使用，若已购买只允许在1台电脑上使用`,
						showCancel: false,
						success: function(res) {
							if (res.confirm) {
								console.log('用户点击确定');
							} else if (res.cancel) {
								console.log('用户点击取消');
							}
						}
					});
					return
				}
				console.log(e);
				// this.content[e.index].active = !e.item.active;
				if (e.index === 0) { // 添加账号
					console.log("点击了添加账号")
					if (this.tableData.length >= this.deviceInfo.maxNumber) {
						uni.showToast({
							title: "超过挂单最大数量",
							icon: "none",
							duration: 2000
						})
						return
					}
					this.userInfo = {}
					console.log(this.userInfo)
					this.opIndex = -1
					this.openPopup()
				} else if (e.index === 1) { //一键登录
					this.loginAll()
				} else if (e.index === 2) { // 一键预约
					this.preBuy()
				} else if (e.index === 3) { // 查看结果
					this.checkSuccessStar()
				}
			},
			// 一键预约
			preBuy() {
				const logoutUserInfo = this.tableData.find(userInfo => userInfo.status === "未登录" && userInfo.option.length > 0)
				if (logoutUserInfo) {
					uni.showToast({
						title: "请先登录再预约",
						duration: 2000
					})
					return
				}
				uni.showLoading({
					title: "预约中..."
				})
				this.preBuyLoading = true
				let index = 0
				this.optionList.map(starInfo => {
					const tempUserInfoList = this.tableData.filter(userInfo => userInfo.option.find(name => name === starInfo.name))
					if (tempUserInfoList.length > 0) {
						setTimeout(() => {
							tempUserInfoList.map(tempUserInfo => {
								this.cyclePreBuy(starInfo, tempUserInfo.token)
							})
						}, index * 2000)
						index++
					}
				})
				setTimeout(() => {
					this.preBuyLoading = false
					uni.hideLoading()
					uni.showToast({
						title: "预约成功，请在“预约成功的星座”栏查看结果",
						icon: "none",
						duration: 5000
					})
					this.checkPreBuyList()
				}, index * 5000)
			},
			checkPreBuyList() {
				this.tableData.map(userInfo => {
					this.$set(userInfo, "preBuyList", "查询中...")
					api.getStarInfoApi(userInfo.token).then(res => {
						const preBuyList = []
						res.data.cat.map(item => {
							if (item.cat_status.status === 1) {
								preBuyList.push(item.name)
							}
						})
						this.$set(userInfo, "preBuyList", preBuyList)
					})
				})
			},
			// 单条预约
			cyclePreBuy(starInfo, token) {
				api.getApi(starInfo.id, token).then(res => {}).catch(e => {
					setTimeout(() => {
						this.cyclePreBuy(starInfo, token)
					}, 1000)
				})
			},
			cycleGetPreBuyStar(index) {
				tempApi.getStarInfoApi(this.tableData[index].token).then(res => {
					const preBuyList = []
					res.data.cat.map(item => {
						if (item.cat_status.status === 1) {
							preBuyList.push(item.name)
						}
					})
					this.$set(this.tableData[index], "preBuyList", preBuyList)
				}).catch(e => {
					this.cycleGetPreBuyStar(index)
				})
			},
			// 一键登录
			loginAll() {
				uni.showLoading({
					title: "登录中"
				})
				setTimeout(() => {
					uni.hideLoading()
				}, 5000)
				this.tableData.map((userInfo, index) => {
					this.loginClickHandle(index)
				})
			},
			loginClickHandle(index) {
				api.loginApi(this.tableData[index].phone, this.tableData[index].password).then(res => {
					if (res.code === 0) {
						this.$set(this.tableData[index], "token", res.data.token)
						this.$set(this.tableData[index], "status", "已登录")
						// 查询用户信息
						api.getUserInfoApi(res.data.token).then(userInfo => {
							this.$set(this.tableData[index], "realname", userInfo.realname)
						})
						// 查询已预约的星座
						this.cycleGetPreBuyStar(index)
						// 查询已成功未处理的星座
						this.cycleSeeSuccessStar(this.tableData[index])
					} else {
						uni.showToast({
							title: res.msg,
							duration: 2000
						})
					}
				}).catch(err => {
					uni.showToast({
						title: res.msg,
						duration: 2000
					})
				})
			},
			checkSuccessStar() {
				this.checkSuccessStarLoading = true
				uni.showLoading({
					title: "查询中"
				})
				setTimeout(() => {
					uni.hideLoading()
					this.checkSuccessStarLoading = false
					uni.showToast({
						title: "查询结束，请再抢购成功的星座栏查看",
						icon: "none",
						duration: 5000
					})
				}, 5000)
				const logoutUserInfo = this.tableData.find(userInfo => userInfo.status === "未登录")
				console.log("logoutUserInfo", logoutUserInfo)
				if (logoutUserInfo) {
					// uni.showToast({
					// 	title: "注意！未登录的账号没有检查漏单",
					// 	icon: "none",
					// 	duration: 2000
					// })
				}
				this.tableData.map(userInfo => {
					this.$set(userInfo, "successStar", "查询中...")
					this.cycleSeeSuccessStar(userInfo)
				})
			},
			cycleSeeSuccessStar(userInfo) {
				api.getSuccessStar(userInfo.token).then(res => {
					const successStar = []
					res.data.data.data.map(item => {
						const star = this.optionList.find(star => star.id === item.cat_id)
						successStar.push(star.name)
					})
					this.$set(userInfo, "successStar", successStar)
				}).catch(e => {
					this.cycleSeeSuccessStar(userInfo)
				})
			},
			comEditAccountChange(e) {
				this.isEditAccountShow = e.show
			},
			comBuyPageChange(e) {
				this.isBuyPageShow = e.show
			},
			buyClickHandle() {
				this.$refs.buyPage.open()
			}
		}
	}
</script>

<style>
	.content {
		display: flex;
		flex-direction: column;
		align-items: center;
		justify-content: center;
	}

	.logo {
		height: 200rpx;
		width: 200rpx;
		margin-top: 200rpx;
		margin-left: auto;
		margin-right: auto;
		margin-bottom: 50rpx;
	}

	.text-area {
		display: flex;
		justify-content: center;
	}

	.title {
		font-size: 36rpx;
		color: #8f8f94;
	}

	.myInput {
		border: 1rpx solid #09BB07;
	}

	.uni-card__footer {
		color: red;
	}
</style>
